﻿using System;
using System.Collections.Generic;
using System.Data;
using System.Linq;
using System.Linq.Expressions;
using System.Text;
using System.Threading.Tasks;
using CNKI.TPI.Web.Base;
using CNKI.TPI.Web.Search.IDAO;
using CNKI.TPI.Web.Search.Model;
using System.Collections;
using KNet.Data.Entity;
using System.Threading;

namespace CNKI.TPI.Web.Search.DAO
{
    class UserDBDAO : BaseDAO, IUserDBDAO
    {
        /// <summary>
        /// 获得指定数据库的发布字段
        /// </summary>
        /// <param name="dbID"></param>
        /// <param name="fieldType"></param>
        /// <returns></returns>
        public IList<SYS_CMS_DATABASE_PUBLISH_FIELD> GetPublishField(int dbID, FieldType fieldType, PermissionOption option = PermissionOption.FilteringPermissions)
        {
            IList<SYS_CMS_DATABASE_PUBLISH_FIELD> result = null;
            try
            {
                //Expression<Func<SYS_CMS_DATABASE_PUBLISH_FIELD, bool>> query = c => (c.DbID == dbID.ToString() && c.FieldType == ((int)fieldType).ToString());
                ExpressionCombine<SYS_CMS_DATABASE_PUBLISH_FIELD> exp = new ExpressionCombine<SYS_CMS_DATABASE_PUBLISH_FIELD>();
                exp.And("DbID", OperatorType.Equal, dbID);
                exp.And("FieldType", OperatorType.Equal, (int)fieldType);
                if (SessionHelper.IsUserInfoExsit() && option == PermissionOption.FilteringPermissions)
                {
                    ExpressionCombine<SYS_CMS_DATABASE_PUBLISH_FIELD> subExp = new ExpressionCombine<SYS_CMS_DATABASE_PUBLISH_FIELD>();
                    IList<string> fieldList = SessionHelper.GetUserField(dbID);

                    if (fieldList != null && fieldList.Count > 0)
                    {
                        fieldList.Add("SYS_FLD_SYSID"); //排序时需要该字段，但是在cmc里对该系统字段不能设置权限
                        fieldList.Add("SYS_FLD_DOWNLOADRATE"); //排序，概览，细缆时需要该字段，但是在cmc里对该系统字段不能设置权限
                        foreach (string item in fieldList)
                        {
                            subExp.Or("FieldName", OperatorType.Equal, item);
                        }
                        exp.And(subExp);
                    }

                }
                result = Context.Get<SYS_CMS_DATABASE_PUBLISH_FIELD>(exp.Compile());
                if (result != null && result.Count > 0)
                {
                    foreach (SYS_CMS_DATABASE_PUBLISH_FIELD item in result)
                    {
                        item.FieldName = StringHelper.RemoveHighlightFlag(item.FieldName);
                    }
                }
            }
            catch (Exception ex)
            {
                LogOpr.Error(ex.ToString());
            }

            return result;
        }

        /// <summary>
        /// 获得跨库检索查询条件字段
        /// </summary>
        /// <param name="dbID"></param>
        /// <param name="fieldType"></param>
        /// <returns></returns>
        public IList<DBUSFIELD> GetUnionPublishField()
        {
            IList<DBUSFIELD> result = null;
            try
            {
                result = Context.GetAll<DBUSFIELD>();
            }
            catch (Exception ex)
            {
                LogOpr.Error(ex.ToString());
            }

            return result;
        }
        /// <summary>
        /// 获得跨库检索查询条件字段
        /// </summary>
        /// <param name="dbID"></param>
        /// <param name="fieldType"></param>
        /// <returns></returns>
        public IList<DBUSFIELD> GetUnionFieldList(FieldType fieldtype)
        {
            IList<DBUSFIELD> result = null;
            try
            {
                ExpressionCombine<DBUSFIELD> exp = new ExpressionCombine<DBUSFIELD>();
                exp.And("FIELDTYPE", OperatorType.Equal, fieldtype);
                result = Context.Get<DBUSFIELD>(exp.Compile());
            }
            catch (Exception ex)
            {
                LogOpr.Error(ex.ToString());
            }

            return result;
        }

        /// <summary>
        /// 获得跨库检索查询数据库
        /// </summary>
        /// <param name="dbID"></param>
        /// <param name="fieldType"></param>
        /// <returns></returns>
        public IList<DBCONFIG> GetUnionDB(string classCode = null)
        {
            IList<DBCONFIG> result = null;
            try
            {
                IList<DBCONFIG> dbList = null;
                if (SessionHelper.IsUserInfoExsit())
                {
                    ExpressionCombine<DBCONFIG> exp = new ExpressionCombine<DBCONFIG>();
                    IList<int> userDBInfo = SessionHelper.GetUserDBRight();
                    if (userDBInfo != null && userDBInfo.Count > 0)
                    {
                        foreach (int item in userDBInfo)
                        {
                            exp.Or("DbID", OperatorType.Equal, item);
                        }
                    }

                    dbList = Context.Get<DBCONFIG>(exp.Compile());
                }
                else
                {
                    dbList = Context.GetAll<DBCONFIG>();
                }

                if (null == classCode)
                {
                    result = dbList;
                }
                else
                {
                    result = new List<DBCONFIG>();
                    string[] classCodeList = null;
                    foreach (DBCONFIG item in dbList)
                    {
                        classCodeList = item.ClassID.Split(new char[] { '|' }, StringSplitOptions.RemoveEmptyEntries);
                        if (classCodeList.Contains(classCode))
                        {
                            result.Add(item);
                        }
                    }
                }
            }
            catch (Exception ex)
            {
                LogOpr.Error(ex.ToString());
            }

            return result;
        }

        /// <summary>
        /// 单库检索
        /// </summary>
        /// <param name="dbID"></param>
        /// <param name="select"></param>
        /// <param name="where"></param>
        /// <param name="pageIndex"></param>
        /// <param name="pageSize"></param>
        /// <returns></returns>
        public DataSet SingleSearch(int dbID, string select, string where, string strGroup, string strOrder, int pageIndex, int pageSize, PermissionOption option = PermissionOption.FilteringPermissions, bool enableCache = true)
        {
            string flage = ConfigHelper.GetAppSettingsValue("getByDrs");
            //目前单库检索强制使用orm检索
            flage = "0";
            DataSet ds = null;
            int startIndex = pageSize * (pageIndex - 1);
            IList<SYS_CMS_DATABASE> dbList = GetDBByID(dbID.ToString());
            if (dbList[0].SearchType == (int)SearchType.TPI)
            {
                ds = MultiSearchByORM(GetDBByID(dbID.ToString()), select, where, strGroup, strOrder, pageIndex, pageSize, option, enableCache: enableCache);
            }
            else
            {
                string db = string.Format("{0}{{{1}}}", DRSManager.GetSingleDrsName(dbID), DRSManager.GetSingleDbSourceName(dbID));
                ds = Context.QueryByDRS(db, select, where, strGroup, strOrder, startIndex, pageSize);
            }
            return ds;
        }

        /// <summary>
        /// 重载多库查询
        /// </summary>
        /// <param name="strdbID"></param>
        /// <param name="select"></param>
        /// <param name="where"></param>
        /// <param name="strGroup"></param>
        /// <param name="strOrder"></param>
        /// <param name="pageIndex"></param>
        /// <param name="pageSize"></param>
        /// <returns></returns>
        public DataSet MultiSearch(IList<SYS_CMS_DATABASE> dbList, string select, string where, string strGroup, string strOrder, int pageIndex, int pageSize, string classCode)
        {
            DataSet ds = null;
            if (IsDBTypeSame(dbList))
            {
                ds = MultiSearchByORM(dbList, select, where, strGroup, strOrder, pageIndex, pageSize);
            }
            else
            {
                ds = MultiSearchNew(dbList, select, where, strGroup, strOrder, pageIndex, pageSize);
            }
            return ds;
        }

        /// <summary>
        /// 重载多库查询
        /// 自动根据数据库的不同来源，分别检索，最后合并结果集并处理
        /// </summary>
        /// <param name="strdbID"></param>
        /// <param name="select"></param>
        /// <param name="where"></param>
        /// <param name="strGroup"></param>
        /// <param name="strOrder"></param>
        /// <param name="pageIndex"></param>
        /// <param name="pageSize"></param>
        /// <returns></returns>
        private DataSet MultiSearchNew(IList<SYS_CMS_DATABASE> dbList, string select, string where, string strGroup, string strOrder, int pageIndex, int pageSize)
        {
            //判断select字段中是否包含排序字段
            bool isSelectContainOrderField;
            string orderField;
            select = PreProcessSelectField(select, strOrder, out isSelectContainOrderField, out orderField);
            //初始化检索结果集
            DataSet ds = InitMultiSearchResult(select);
            object lockObj = new object();
            IList<Thread> threadList = new List<Thread>();
            //检索自建库非Unicode数据
            IList<SYS_CMS_DATABASE> tempList = dbList.Where(c => c.SearchType == 0 && c.IsUnicode == 0 && c.RecordCheckPubFlag == 0).ToList();
            if (tempList != null && tempList.Count > 0)
            {
                Thread t = new Thread(new ParameterizedThreadStart(SearchCnki));
                SearchParam sp = InitSearchParam(select, where, strGroup, strOrder, pageIndex, pageSize, ds, lockObj, tempList);
                t.Start(sp);
                threadList.Add(t);
            }
            tempList = dbList.Where(c => c.SearchType == 0 && c.IsUnicode == 0 && c.RecordCheckPubFlag == 1).ToList();
            if (tempList != null && tempList.Count > 0)
            {
                Thread t = new Thread(new ParameterizedThreadStart(SearchCnki));
                SearchParam sp = InitSearchParam(select, where, strGroup, strOrder, pageIndex, pageSize, ds, lockObj, tempList);
                t.Start(sp);
                threadList.Add(t);
            }
            //检索自建库Unicode数据
            tempList = dbList.Where(c => c.SearchType == 0 && c.IsUnicode == 1 && c.RecordCheckPubFlag == 0).ToList();
            if (tempList != null && tempList.Count > 0)
            {
                Thread t = new Thread(new ParameterizedThreadStart(SearchCnki));
                SearchParam sp = InitSearchParam(select, where, strGroup, strOrder, pageIndex, pageSize, ds, lockObj, tempList);
                t.Start(sp);
                threadList.Add(t);
            }
            tempList = dbList.Where(c => c.SearchType == 0 && c.IsUnicode == 1 && c.RecordCheckPubFlag == 1).ToList();
            if (tempList != null && tempList.Count > 0)
            {
                Thread t = new Thread(new ParameterizedThreadStart(SearchCnki));
                SearchParam sp = InitSearchParam(select, where, strGroup, strOrder, pageIndex, pageSize, ds, lockObj, tempList);
                t.Start(sp);
                threadList.Add(t);
            }
            //通过drs检索数据
            tempList = dbList.Where(c => c.SearchType != 0).ToList();
            if (tempList != null && tempList.Count > 0)
            {
                Thread t = new Thread(new ParameterizedThreadStart(SearchOther));
                SearchParam sp = InitSearchParam(select, where, strGroup, strOrder, pageIndex, pageSize, ds, lockObj, tempList);
                t.Start(sp);
                threadList.Add(t);
            }
            //等待检索完成
            Array.ForEach<Thread>(threadList.ToArray(), t =>
    {
        t.Join();
    });
            //重新排序及分页
            PostProcessResult(strOrder, pageIndex, pageSize, isSelectContainOrderField, orderField, ds);

            return ds;
        }

        private void PostProcessResult(string strOrder, int pageIndex, int pageSize, bool isSelectContainOrderField, string orderField, DataSet ds)
        {
            DataView dv = ds.Tables[0].DefaultView;
            dv.Sort = strOrder;
            DataTable infoTable = ds.Tables[1];
            DataTable dataTable = dv.ToTable();
            if (!isSelectContainOrderField)
            {
                dataTable.Columns.Remove(orderField);
            }

            DataTable newDataTable = dataTable.Clone();
            int lastRecordIndex = dataTable.Rows.Count > pageIndex * pageSize ? pageIndex * pageSize : dataTable.Rows.Count;
            for (int i = (pageIndex - 1) * pageSize; i < lastRecordIndex; i++)
            {
                newDataTable.ImportRow(dataTable.Rows[i]);
            }

            ds.Tables.Clear();
            ds.Tables.Add(newDataTable);
            ds.Tables.Add(infoTable);
        }

        private string PreProcessSelectField(string select, string strOrder, out bool isSelectContainOrderField, out string orderField)
        {
            isSelectContainOrderField = true;

            orderField = strOrder.Substring(0, strOrder.IndexOf(' '));
            if (select.Contains(','))
            {
                string[] fieldList = select.Split(new string[] { "," }, StringSplitOptions.RemoveEmptyEntries);
                if (!fieldList.Contains(orderField))
                {
                    select = select + "," + orderField;
                    isSelectContainOrderField = false;
                }
            }
            else if (!select.Equals(orderField))
            {
                select = select + "," + orderField;
                isSelectContainOrderField = false;
            }
            return select;
        }

        private SearchParam InitSearchParam(string select, string where, string strGroup, string strOrder, int pageIndex, int pageSize, DataSet ds, object lockObj, IList<SYS_CMS_DATABASE> tempList)
        {
            SearchParam sp = new SearchParam();
            sp.DbList = tempList;
            sp.Select = select;
            sp.Where = where;
            sp.StrGroup = strGroup;
            sp.StrOrder = strOrder;
            sp.PageIndex = pageIndex;
            sp.PageSize = pageSize;
            sp.Result = ds;
            sp.LockObj = lockObj;
            return sp;
        }

        public void SearchCnki(object param)
        {
            try
            {
                SearchParam paramList = (SearchParam)param;
                DataSet tempDs = MultiSearchByORM(paramList.DbList, paramList.Select, paramList.Where, paramList.StrGroup, paramList.StrOrder, 1, paramList.PageIndex * paramList.PageSize);
                DataSet result = paramList.Result;
                MergeDateSet(paramList.LockObj, tempDs, ref result);
            }
            catch (Exception ex)
            {
                LogOpr.Error(ex.ToString());
            }
        }

        public void SearchOther(object param)
        {
            try
            {
                SearchParam paramList = (SearchParam)param;
                DataSet tempDs = MultiSearchByDRS(string.Join(",", paramList.DbList.Select(c => c.SysID)), paramList.Select, paramList.Where, paramList.StrGroup, paramList.StrOrder, 1, paramList.PageIndex * paramList.PageSize);
                DataSet result = paramList.Result;
                MergeDateSet(paramList.LockObj, tempDs, ref result);
            }
            catch (Exception ex)
            {
                LogOpr.Error(ex.ToString());
            }
        }

        private DataSet InitMultiSearchResult(string select)
        {
            DataSet ds = new DataSet();
            DataTable dt1 = new DataTable();
            foreach (string item in select.Split(new string[] { "," }, StringSplitOptions.RemoveEmptyEntries))
            {
                dt1.Columns.Add(item);
            }
            dt1.Columns.Add("__sys_from");
            dt1.Columns.Add("__sys_link");
            dt1.Columns.Add("__sys_type");
            dt1.Columns.Add("__sys_name");
            dt1.Columns.Add("__sys_weight");
            ds.Tables.Add(dt1);

            DataTable dt2 = new DataTable("infos");
            dt2.Columns.Add("code");
            dt2.Columns.Add("name");
            dt2.Columns.Add("count", typeof(Int32));
            ds.Tables.Add(dt2);
            return ds;
        }

        private void MergeDateSet(object lockObj, DataSet src, ref DataSet target)
        {
            lock (lockObj)
            {
                object[] obj = new object[target.Tables[0].Columns.Count];

                for (int i = 0; i < src.Tables[0].Rows.Count; i++)
                {
                    src.Tables[0].Rows[i].ItemArray.CopyTo(obj, 0);
                    target.Tables[0].Rows.Add(obj);
                }

                //target.Tables[0].Merge(src.Tables[0]);
                target.Tables[1].Merge(src.Tables[1]);
            }
        }

        /// <summary>
        /// 判断数据库是否是同一个类型（Unicode，ascii）
        /// </summary>
        /// <returns></returns>
        private bool IsDBTypeSame(IList<SYS_CMS_DATABASE> dbList)
        {
            bool result = true;
            //string[] dbIDList = strdbID.Split(new[] { ',' }, StringSplitOptions.RemoveEmptyEntries);
            //判断是否都是TPI库
            if (dbList.Where(c => c.SearchType == (int)SearchType.TPI).ToList().Count != dbList.Count)
            {
                return false;
            }
            //判断是否都是同一个编码类型
            if (dbList != null && dbList.Count > 1)
            {
                for (int i = 1; i < dbList.Count; i++)
                {
                    if (dbList[i].IsUnicode != dbList[i - 1].IsUnicode || dbList[i].RecordCheckPubFlag != dbList[i - 1].RecordCheckPubFlag)
                    {
                        result = false;
                        break;
                    }
                }
            }
            return result;
        }

        /// <summary>
        /// 判断数据库是否是同一个类型（Unicode，ascii）
        /// </summary>
        /// <returns></returns>
        private bool IsDBTypeSame(string strdbID, out IList<SYS_CMS_DATABASE> dbList)
        {
            bool result = true;
            //string[] dbIDList = strdbID.Split(new[] { ',' }, StringSplitOptions.RemoveEmptyEntries);
            dbList = GetDBByID(strdbID);
            //判断是否都是TPI库
            if (dbList.Where(c => c.SearchType == (int)SearchType.TPI).ToList().Count != dbList.Count)
            {
                return false;
            }
            //判断是否都是同一个编码类型
            if (dbList != null && dbList.Count > 1)
            {
                for (int i = 1; i < dbList.Count; i++)
                {
                    if (dbList[i].IsUnicode != dbList[i - 1].IsUnicode)
                    {
                        result = false;
                        break;
                    }
                }
            }
            return result;
        }

        /// <summary>
        /// 使用drs检索数据
        /// </summary>
        /// <param name="strdbID"></param>
        /// <param name="select"></param>
        /// <param name="where"></param>
        /// <param name="strGroup"></param>
        /// <param name="strOrder"></param>
        /// <param name="pageIndex"></param>
        /// <param name="pageSize"></param>
        /// <returns></returns>
        private DataSet MultiSearchByDRS(string strdbID, string select, string where, string strGroup, string strOrder, int pageIndex, int pageSize)
        {
            string security = "";
            //if (SessionHelper.IsUserInfoExsit())
            //if (false)
            //{
            //    IList<string> securityLevel = SessionHelper.GetUserSecurity();
            //    if (securityLevel != null)
            //    {
            //        security = string.Join(" Or ", securityLevel.Select(c => string.Format("SYS_FLD_SECURITY Eq '{0}'", c)));
            //    }
            //}
            if (!string.IsNullOrEmpty(security))
            {
                if (!string.IsNullOrEmpty(where))
                {
                    where = string.Format("({0}) And ({1})", where, security);
                }
                else
                {
                    where = security;
                }
            }
            string[] arraydbid = null;
            if (strdbID != "")
            {
                arraydbid = strdbID.Split(',');
                for (int i = 0; i < arraydbid.Length; i++)
                {
                    arraydbid[i] = DRSManager.GetMultiDbSourceName(int.Parse(arraydbid[i]));
                }
            }
            string multidbid = arraydbid == null ? "" : string.Join(",", arraydbid);
            int startIndex = pageSize * (pageIndex - 1);
            return Context.QueryByDRS(string.Format("{0}{{{1}}}", DRSManager.GetMultiDrsName(), multidbid), select, where, strGroup, strOrder, startIndex, pageSize);
        }

        /// <summary>
        /// 使用本地方法检索
        /// </summary>
        /// <param name="strdbID"></param>
        /// <param name="select"></param>
        /// <param name="where"></param>
        /// <param name="strGroup"></param>
        /// <param name="strOrder"></param>
        /// <param name="pageIndex"></param>
        /// <param name="pageSize"></param>
        /// <returns></returns>
        private DataSet MultiSearchByORM(IList<SYS_CMS_DATABASE> dbList, string select, string where, string strGroup, string strOrder, int pageIndex, int pageSize, PermissionOption option = PermissionOption.FilteringPermissions, bool enableCache = true)
        {
            DataSet ds = new DataSet();
            if (dbList != null && dbList.Count > 0)
            {
                //from
                string from = string.Join(",", dbList.Select(c => c.SearchType == (int)SearchType.TPI ? c.DatabaseCode + "_METADATA" : c.DatabaseCode));
                bool isUnicode = dbList[0].IsUnicode == 1 ? true : false;
                int nonTPICount = dbList.Where(c => (SearchType)c.SearchType != SearchType.TPI).ToList().Count;
                //where条件
                string security = "";
                if (SessionHelper.IsUserInfoExsit() && option == PermissionOption.FilteringPermissions && nonTPICount == 0)
                {
                    IList<string> securityLevel = SessionHelper.GetUserSecurity();
                    if (securityLevel != null)
                    {
                        security = string.Join(" Or ", securityLevel.Select(c => string.Format("SYS_FLD_SECURITY Eq '{0}'", c)));
                    }

                    if (!string.IsNullOrEmpty(security))
                    {
                        if (!string.IsNullOrEmpty(where))
                        {
                            where = string.Format("({0}) And ({1})", where, security);
                        }
                        else
                        {
                            where = security;
                        }
                    }

                    if (dbList[0].RecordCheckPubFlag == 1) //审核标识
                    {
                        if (!string.IsNullOrEmpty(where))
                        {
                            if (where.IndexOf("SYS_FLD_CHECKSTATE Eq") < 0)//如果没有加查询条件SYS_FLD_CHECKSTATE 则加上
                            {
                                where = string.Format("({0}) And (SYS_FLD_CHECKSTATE Eq 2)", where);
                            }
                        }
                        else
                        {
                            where = "SYS_FLD_CHECKSTATE Eq 2";
                        }
                    }
                }

                //分页
                string limit = pageSize * (pageIndex - 1) + "," + pageSize;
                StringBuilder sql1 = new StringBuilder();
                //if (isUnicode)
                //{
                //    sql1.Append("unicode:");
                //}
                sql1.AppendFormat("select {0} from {1} ", select + ",getsysfield(__tablename)", from);
                if (!String.IsNullOrEmpty(where))//存在where条件,对where条件进行处理
                {
                    where = DealWhere(where);
                    sql1.AppendFormat(" where {0} ", where);
                }
                if (!String.IsNullOrEmpty(strGroup))//存在分组条件
                {
                    sql1.AppendFormat(" group by {0} ", strGroup);
                }
                if (!String.IsNullOrEmpty(strOrder))//存在排序条件
                {
                    sql1.AppendFormat(" order by {0} ", strOrder);
                }
                ds = Context.ExecuteSql(sql1.ToString(), dbList.Select(c => c.DatabaseCode + "_METADATA").ToList(), pageIndex, pageSize, isUnicode, dataCacheTimeout: enableCache ? ConfigHelper.GetDataCacheTimeout() : 0);
                //sql1.AppendFormat(" limit {0} ", limit);
                //DataTable dt = Context.ExecuteSql(sql1.ToString(), dataCacheTimeout: enableCache ? ConfigHelper.GetDataCacheTimeout() : 0);
                ProcessDT(ds.Tables[0], dbList);
                //ds.Tables.Add(dt);

                DataTable infoList = BuildInfos(dbList, ds);
                ds.Tables.RemoveAt(1);
                ds.Tables.Add(infoList);
            }
            return ds;
        }
        /// <summary>
        /// 处理查询条件
        /// </summary>
        /// <param name="where"></param>
        /// <returns></returns>
        private string DealWhere(string where)
        {
            where = where.Replace(" Eq ", " = ");
            where = where.Replace(" Like ", " % ");
            where = where.Replace(" GreaterThan ", " > ");
            where = where.Replace(" GreaterThanOrEqual ", " >= ");
            where = where.Replace(" LessThan ", " < ");
            where = where.Replace(" LessThanOrEqual ", " <= ");
            string[] dealStr = where.Split(new string[] { " Ne " }, StringSplitOptions.RemoveEmptyEntries);
            int len = dealStr.Count();
            if (len > 1)
            {
                for (int i = 0; i < len - 1; i++)
                {
                    int lastlen = dealStr[i].ToString().LastIndexOf(' ');
                    int last2 = dealStr[i].ToString().LastIndexOf('(');
                    int location = lastlen;
                    if (last2 > lastlen)
                    {
                        location = last2;
                    }
                    string keystr = dealStr[i].Substring(location + 1);
                    dealStr[i] = dealStr[i] + " =* not " + keystr + " =";

                }

            }
            return string.Join("", dealStr);

        }

        private DataTable BuildInfos(IList<SYS_CMS_DATABASE> dbList, string where)
        {
            DataTable dt = null;
            bool isUnicode = dbList[0].IsUnicode == 1 ? true : false;
            DataTable infoList = InitInfoTable();
            string sql2 = "select count(*) from {0} where {1}";
            string count = null;
            DataRow dr = null;
            foreach (SYS_CMS_DATABASE item in dbList)
            {
                if (isUnicode)
                {
                    if ((SearchType)item.SearchType == SearchType.TPI)
                    {
                        dt = Context.ExecuteSql("unicode:" + string.Format(sql2, item.DatabaseCode + "_METADATA", where));
                    }
                    else
                    {
                        dt = Context.ExecuteSql("unicode:" + string.Format(sql2, item.DatabaseCode, where));
                    }

                }
                else
                {
                    if ((SearchType)item.SearchType == SearchType.TPI)
                    {
                        dt = Context.ExecuteSql(string.Format(sql2, item.DatabaseCode + "_METADATA", where));
                    }
                    else
                    {
                        dt = Context.ExecuteSql(string.Format(sql2, item.DatabaseCode, where));
                    }

                }
                if (dt != null && dt.Rows.Count > 0)
                {
                    count = dt.Rows[0][0].ToString();
                    dr = infoList.NewRow();
                    dr["code"] = item.DatabaseCode;
                    dr["count"] = count;
                    dr["name"] = item.SysID + "#" + item.DatabaseCode + "#" + item.DatabaseName + "#" + DRSManager.GetDBType(item.DatabaseType);
                    infoList.Rows.Add(dr);
                }
                else
                {
                    dr = infoList.NewRow();
                    dr["code"] = item.DatabaseCode;
                    dr["count"] = "0";
                    dr["name"] = item.SysID + "#" + item.DatabaseCode + "#" + item.DatabaseName + "#" + DRSManager.GetDBType(item.DatabaseType);
                    infoList.Rows.Add(dr);
                }
            }
            return infoList;
        }

        private DataTable BuildInfos(IList<SYS_CMS_DATABASE> dbList, DataSet ds)
        {
            bool isUnicode = dbList[0].IsUnicode == 1 ? true : false;
            DataTable infoList = InitInfoTable();
            string count = null;
            DataRow[] drList = null;
            DataRow dr = null;
            DataTable info = ds.Tables[1];
            foreach (SYS_CMS_DATABASE item in dbList)
            {
                drList = info.Select("name = '" + item.DatabaseCode + "_METADATA'");
                if (drList != null && drList.Count() > 0)
                {
                    count = drList[0][1].ToString();
                    dr = infoList.NewRow();
                    dr["code"] = item.DatabaseCode;
                    dr["count"] = count;
                    dr["name"] = item.SysID + "#" + item.DatabaseCode + "#" + item.DatabaseName + "#" + DRSManager.GetDBType(item.DatabaseType);
                    infoList.Rows.Add(dr);
                }
                else
                {
                    dr = infoList.NewRow();
                    dr["code"] = item.DatabaseCode;
                    dr["count"] = "0";
                    dr["name"] = item.SysID + "#" + item.DatabaseCode + "#" + item.DatabaseName + "#" + DRSManager.GetDBType(item.DatabaseType);
                    infoList.Rows.Add(dr);
                }
            }
            return infoList;
        }
        private void ProcessDT(DataTable dt, IList<SYS_CMS_DATABASE> dbList)
        {
            string tableName = null;
            dt.Columns.Add("__sys_from");
            dt.Columns.Add("__sys_link");
            dt.Columns.Add("__sys_type");
            dt.Columns.Add("__sys_name");
            dt.Columns.Add("__sys_weight");
            foreach (DataRow dr in dt.Rows)
            {
                tableName = dr["getsysfield(__tablename)"].ToString();
                dr["__sys_from"] = BuildDBInfo(tableName, dbList);
            }
            if (dt.Columns.Contains("getsysfield(__tablename)"))
            {
                dt.Columns.Remove("getsysfield(__tablename)");
            }
        }
        private string BuildDBInfo(string tableName, IList<SYS_CMS_DATABASE> dbList)
        {

            SYS_CMS_DATABASE dbInfo = null;
            foreach (SYS_CMS_DATABASE item in dbList)
            {
                if (item.SearchType == (int)SearchType.TPI && item.DatabaseCode.ToUpper() + "_METADATA" == tableName.ToUpper())
                {
                    dbInfo = item;
                    break;
                }
                else if (item.SearchType != (int)SearchType.TPI && item.DatabaseCode.ToUpper() == tableName.ToUpper())
                {
                    dbInfo = item;
                    break;
                }
            }
            if (null == dbInfo)
            {
                return "";
            }
            else
            {
                return dbInfo.SysID + "#" + dbInfo.DatabaseCode + "#" + dbInfo.DatabaseName + "#" + DRSManager.GetDBType(dbInfo.DatabaseType);
            }
        }

        private DataTable InitInfoTable()
        {
            DataTable dt = new DataTable("infos");
            dt.Columns.Add("code");
            dt.Columns.Add("name");
            dt.Columns.Add("count", typeof(Int32));
            return dt;
        }

        /// <summary>
        /// 获取文件
        /// </summary>
        /// <param name="recordID"></param>
        /// <param name="dbName"></param>
        /// <returns></returns>
        public IList<METADATA_FILE> GetFile(int recordID, string dbName)
        {
            IList<METADATA_FILE> result = null;
            try
            {
                string sql = @"select RECORDID,DOI,RESOURCETYPE,FORMAT,CONTENTTYPE,
                                FULLTEXT,FILELINKURL,FILEDESCRIPT,UPLOADUSERNAME,
                                UPLOADTIME,FILENAME,FILESIZE,MD5CODE,READONLINE,
                                SORTNUMBER,CONTENTFLAG,SYSID from {0}_METADATA_FILE where RECORDID='{1}'";
                IList<METADATA_FILE> itemList = Context.ExecuteSql<METADATA_FILE>(string.Format(sql, dbName, recordID));
                if (itemList != null && itemList.Count > 0)
                {
                    result = itemList;
                }
            }
            catch (Exception ex)
            {
                LogOpr.Error(ex.ToString());
            }
            return result;
        }

        /// <summary>
        /// 
        /// </summary>
        /// <param name="fileID"></param>
        /// <param name="dbName"></param>
        /// <returns></returns>
        public METADATA_FILE GetSingleFile(int fileID, string dbName)
        {
            METADATA_FILE result = null;
            try
            {
                string sql = @"select RECORDID,DOI,RESOURCETYPE,FORMAT,CONTENTTYPE,
                                FULLTEXT,FILELINKURL,FILEDESCRIPT,UPLOADUSERNAME,
                                UPLOADTIME,FILENAME,FILESIZE,MD5CODE,READONLINE,
                                SORTNUMBER,CONTENTFLAG,SYSID from {0}_METADATA_FILE where SysID='{1}'";
                IList<METADATA_FILE> itemList = Context.ExecuteSql<METADATA_FILE>(string.Format(sql, dbName, fileID));
                if (itemList != null && itemList.Count > 0)
                {
                    result = itemList[0];
                }
            }
            catch (Exception ex)
            {
                LogOpr.Error(ex.ToString());
            }
            return result;
        }

        /// <summary>
        /// 
        /// </summary>
        /// <param name="fileID"></param>
        /// <param name="dbName"></param>
        /// <returns></returns>
        public METADATA_FILE_IMAGE GetSmallPic(int fileID, string dbName)
        {
            METADATA_FILE_IMAGE result = null;
            try
            {
                string sql = @"select FILEID,IMAGEFILENAME,IMAGEFILESIZE,WIDTH,HEIGHT,RESAMPLETYPE,COLORBIT,DPI,IMAGEFILEEXT,SYSID
                                from {0}_METADATA_FILE_IMAGE where FILEID='{1}'";
                IList<METADATA_FILE_IMAGE> itemList = Context.ExecuteSql<METADATA_FILE_IMAGE>(string.Format(sql, dbName, fileID));
                if (itemList != null && itemList.Count > 0)
                {
                    result = itemList[0];
                }
            }
            catch (Exception ex)
            {
                LogOpr.Error(ex.ToString());
            }
            return result;
        }

        /// <summary>
        /// 获得跨库检索分类
        /// </summary>
        /// <returns></returns>
        public IList<DBCLASS> GetUnionClass()
        {
            IList<DBCLASS> result = null;
            try
            {
                Expression<Func<DBCLASS, bool>> order = c => c.SortNum.Asc();
                result = Context.GetAll<DBCLASS>(order);
            }
            catch (Exception ex)
            {
                LogOpr.Error(ex.ToString());
            }

            return result;
        }

        /// <summary>
        /// 获得数据库列表
        /// </summary>
        /// <returns></returns>
        public IList<SYS_CMS_DATABASE> GetDatabaseList()
        {
            ExpressionCombine<SYS_CMS_DATABASE> exp = new ExpressionCombine<SYS_CMS_DATABASE>();
            if (SessionHelper.IsUserInfoExsit())
            {
                ExpressionCombine<SYS_CMS_DATABASE> subExp2 = new ExpressionCombine<SYS_CMS_DATABASE>();
                IList<int> userDBInfo = SessionHelper.GetUserDBRight();
                if (userDBInfo != null && userDBInfo.Count > 0)
                {
                    foreach (int item in userDBInfo)
                    {
                        subExp2.Or("SysID", OperatorType.Equal, item);
                    }
                    exp.And(subExp2);
                }

                IList<string> securityLevel = SessionHelper.GetUserSecurity();
                if (securityLevel != null && securityLevel.Count > 0)
                {
                    ExpressionCombine<SYS_CMS_DATABASE> subExp3 = new ExpressionCombine<SYS_CMS_DATABASE>();
                    foreach (string security in securityLevel)
                    {
                        subExp3.Or("Secrity", OperatorType.Equal, security);
                    }
                    exp.And(subExp3);
                }
            }
            return Context.Get<SYS_CMS_DATABASE>(exp.Compile());
        }

        /// <summary>
        /// 获得数据库列表
        /// </summary>
        /// <returns></returns>
        public IList<SYS_CMS_DATABASE> GetDatabaseList(int pageIndex, int pageSize, out int count)
        {
            ExpressionCombine<SYS_CMS_DATABASE> exp = new ExpressionCombine<SYS_CMS_DATABASE>();
            if (SessionHelper.IsUserInfoExsit())
            {
                ExpressionCombine<SYS_CMS_DATABASE> subExp2 = new ExpressionCombine<SYS_CMS_DATABASE>();
                IList<int> userDBInfo = SessionHelper.GetUserDBRight();
                if (userDBInfo != null && userDBInfo.Count > 0)
                {
                    foreach (int item in userDBInfo)
                    {
                        subExp2.Or("SysID", OperatorType.Equal, item);
                    }
                    exp.And(subExp2);
                }

                IList<string> securityLevel = SessionHelper.GetUserSecurity();
                if (securityLevel != null && securityLevel.Count > 0)
                {
                    ExpressionCombine<SYS_CMS_DATABASE> subExp3 = new ExpressionCombine<SYS_CMS_DATABASE>();
                    foreach (string security in securityLevel)
                    {
                        subExp3.Or("Secrity", OperatorType.Equal, security);
                    }
                    exp.And(subExp3);
                }
            }
            return Context.Get<SYS_CMS_DATABASE>(exp.Compile(), pageIndex, pageSize, out count);
        }
        /// <summary>
        /// 根据数据库名称获得数据库列表
        /// </summary>
        /// <returns></returns>
        public IList<SYS_CMS_DATABASE> GetDatabaseList(int pageIndex, int pageSize, out int count, string dbname, IList<SearchType> SearchTypeList = null)
        {
            ExpressionCombine<SYS_CMS_DATABASE> exp = new ExpressionCombine<SYS_CMS_DATABASE>();

            if (SessionHelper.IsUserInfoExsit())
            {
                ExpressionCombine<SYS_CMS_DATABASE> subExp2 = new ExpressionCombine<SYS_CMS_DATABASE>();
                IList<int> userDBInfo = SessionHelper.GetUserDBRight();
                if (userDBInfo != null && userDBInfo.Count > 0)
                {
                    foreach (int item in userDBInfo)
                    {
                        subExp2.Or("SysID", OperatorType.Equal, item);
                    }
                    exp.And(subExp2);
                }

                IList<string> securityLevel = SessionHelper.GetUserSecurity();
                if (securityLevel != null && securityLevel.Count > 0)
                {
                    ExpressionCombine<SYS_CMS_DATABASE> subExp3 = new ExpressionCombine<SYS_CMS_DATABASE>();
                    foreach (string security in securityLevel)
                    {
                        subExp3.Or("Secrity", OperatorType.Equal, security);
                    }
                    exp.And(subExp3);
                }
            }

            if (!String.IsNullOrEmpty(dbname))
            {
                ExpressionCombine<SYS_CMS_DATABASE> subExp4 = new ExpressionCombine<SYS_CMS_DATABASE>();
                subExp4.And("DatabaseName", OperatorType.Like, dbname);
                exp.And(subExp4);
            }

            if (SearchTypeList != null)
            {
                if (SearchTypeList.Count == 0)
                {
                    count = 0;
                    return new List<SYS_CMS_DATABASE>();
                }
                ExpressionCombine<SYS_CMS_DATABASE> subExp4 = new ExpressionCombine<SYS_CMS_DATABASE>();
                foreach (SearchType item in SearchTypeList)
                {
                    subExp4.Or("SearchType", OperatorType.Equal, (int)item);
                }
                exp.And(subExp4);
            }

            return Context.Get<SYS_CMS_DATABASE>(exp.Compile(), pageIndex, pageSize, out count);
        }

        /// <summary>
        /// 
        /// </summary>
        /// <param name="databaseCode"></param>
        /// <returns></returns>
        public IList<SYS_CMS_DATABASE> GetDBByID(string strdataID)
        {

            IList<SYS_CMS_DATABASE> result = null;
            try
            {
                if (strdataID != "")
                {
                    string[] databaseID = strdataID.Split(',');
                    ExpressionCombine<SYS_CMS_DATABASE> exp = new ExpressionCombine<SYS_CMS_DATABASE>();
                    foreach (string item in databaseID)
                    {
                        exp.Or("SysID", OperatorType.Equal, item);
                    }
                    result = Context.Get<SYS_CMS_DATABASE>(exp.Compile());
                }
            }
            catch (Exception ex)
            {
                LogOpr.Error(ex.ToString());
            }

            return result;
        }

        public int[] GetUserDownloadInfo(int dbID, string userID)
        {
            int[] result = { 0, 0 };
            string sql = @"select a.dayCount, a.daycount+c.totalCount
                            from (SELECT ifnull(count(down.DownloadLogID),0) dayCount FROM tpi.downloadlog down where DATE_FORMAT(OperateTime, '%Y-%m-%d') = '{2}' and userid = {0} and dbid = {1} and (source = 0 or source = 2)) a
                            inner join (select ifnull(sum(b.download),0) totalCount from tpi.accessstatistics b where b.userid={0} and b.dbid = {1}) c on 1=1";

            DataTable dt = Context.ExecuteSql(string.Format(sql, userID, dbID, DateTime.Now.ToString("yyyy-MM-dd")), "mysql");
            if (dt != null && dt.Rows.Count > 0)
            {
                foreach (DataRow dr in dt.Rows)
                {
                    result[0] = Convert.ToInt32(dr[0]);
                    result[1] = Convert.ToInt32(dr[1]);
                }
            }
            return result;
        }

        /// <summary>
        /// 根据用户ID和时间段获取检索词
        /// </summary>
        /// <param name="userID"></param>
        /// <param name="startdate"></param>
        /// <param name="enddate"></param>
        /// <returns></returns>
        public string GetQueryByUserCode(string userCode)
        {
            string result = "";
            try
            {
                string sql = @"SELECT RecommendInfo FROM tpi.userrecommendinfo where UserCode = '{0}';";
                DataTable dt = Context.ExecuteSql(string.Format(sql, userCode), "mysql");
                if (dt != null && dt.Rows.Count > 0)
                {
                    if (!string.IsNullOrEmpty(dt.Rows[0][0].ToString()))
                    {
                        result = dt.Rows[0][0].ToString();
                    }
                }
            }
            catch (Exception ex)
            {
                result = "-1";
                LogOpr.Error(ex.ToString());
            }
            return result;
        }

        /// <summary>
        /// 删除METADATA 记录
        /// </summary>
        /// <param name="sysid"></param>
        /// <param name="dbCode"></param>
        /// <returns></returns>
        public bool DelMetaData(int sysid, string dbCode)
        {
            bool result = false;
            try
            {
                string sql = "delete from {0}_METADATA where SYS_FLD_SYSID={1}";
                sql = string.Format(sql, dbCode, sysid);
                result = Context.ExecuteNonQuery(sql);
            }
            catch (Exception ex)
            {
                LogOpr.Error(ex.ToString());
            }
            return result;
        }

        /// <summary>
        /// 更新METADATA 记录
        /// </summary>
        /// <param name="sysid"></param>
        /// <param name="dbCode"></param>
        /// <returns></returns>
        public bool UpdateMetaData(string sysid, string dbCode, Dictionary<string, object> fieldList, bool isUnicode)
        {
            bool result = false;
            try
            {
                StringBuilder str = new StringBuilder("<REC>");
                str.Append("<SYS_FLD_SYSID>=" + sysid);
                foreach (string item in fieldList.Keys)
                {
                    str.Append(string.Format("<{0}>={1}", item, fieldList[item]));
                }
                DateTime dt = DateTime.Now;
                str.Append("<SYS_FLD_RECORDUPDATEDATE>=" + dt.ToString("yyyy-MM-dd HH:mm:ss"));
                if (SessionHelper.IsUserInfoExsit())
                {
                    str.Append("<SYS_FLD_RESOURCEOWNER>=" + SessionHelper.GetUserInfo().UserCode);
                }
                str.Append("<SYS_FLD_CHECKSTATE>=0");
                result = Context.UpdateRec(sysid, dbCode + "_METADATA", str.ToString(), isUnicode);
            }
            catch (Exception ex)
            {
                LogOpr.Error(ex.ToString());
            }
            return result;
        }

        /// <summary>
        /// 插入METADATA 记录
        /// </summary>
        /// <param name="sysid"></param>
        /// <param name="dbCode"></param>
        /// <returns></returns>
        public int InsertMetaData(string dbCode, Dictionary<string, object> fieldList, bool isUnicode)
        {
            int result = 0;
            try
            {
                StringBuilder str = new StringBuilder("<REC>");
                foreach (string item in fieldList.Keys)
                {
                    str.Append(string.Format("<{0}>={1}", item, fieldList[item]));
                }
                DateTime dt = DateTime.Now;
                str.Append("<SYS_FLD_RECORDADDDATE>=" + dt.ToString("yyyy-MM-dd HH:mm:ss"));
                str.Append("<SYS_FLD_RECORDUPDATEDATE>=" + dt.ToString("yyyy-MM-dd HH:mm:ss"));
                if (SessionHelper.IsUserInfoExsit())
                {
                    str.Append("<SYS_FLD_RESOURCEOWNER>=" + SessionHelper.GetUserInfo().UserCode);
                }
                str.Append("<SYS_FLD_CHECKSTATE>=0");
                result = Context.InsertRec(dbCode + "_METADATA", str.ToString(), isUnicode);

                //string sql = "INSERT INTO {0}_METADATA ({1}) VALUES({2})";
                //string fields = string.Join(",", fieldList.Select(c => c.Key));
                //string values = string.Join("','", fieldList.Select(c => c.Value));
                //if (!string.IsNullOrEmpty(values))
                //{
                //    values = "'" + values + "'";
                //}
                //sql = string.Format(sql, dbCode, fields, values);
                //result = Context.ExecuteNonQuery(sql);
            }
            catch (Exception ex)
            {
                LogOpr.Error(ex.ToString());
            }
            return result;
        }

        /// <summary>
        /// 得到满足条件的结果集的记录数---LZG添加
        /// </summary>
        /// <param name="Sql">Sql语句</param>
        /// <returns>记录数目</returns>
        public IList<SYS_CMS_SUBMIT> GetSubmitConfig(string dbcode)
        {
            IList<SYS_CMS_SUBMIT> result = null;
            try
            {
                //论文提交(flag=2)、在线提交(flag=1)
                ExpressionCombine<SYS_CMS_SUBMIT> exp = new ExpressionCombine<SYS_CMS_SUBMIT>();
                exp.And("DBCODE", OperatorType.Equal, dbcode);
                result = Context.Get<SYS_CMS_SUBMIT>(exp.Compile());
            }
            catch (Exception ex)
            {
                LogOpr.Error(ex.ToString());
            }
            return result;
        }

        public IList<SYS_CMS_SUBMIT> GetSubmitConfig(string dbcode, string fieldname, SubmitFieldType fieldType)
        {
            IList<SYS_CMS_SUBMIT> result = null;
            try
            {
                //论文提交(flag=2)、在线提交(flag=1)
                ExpressionCombine<SYS_CMS_SUBMIT> exp = new ExpressionCombine<SYS_CMS_SUBMIT>();
                exp.And("DBCODE", OperatorType.Equal, dbcode);
                exp.And("FIELDNAME", OperatorType.Equal, fieldname);
                exp.And("FIELDTYPE", OperatorType.Equal, (int)fieldType);
                result = Context.Get<SYS_CMS_SUBMIT>(exp.Compile());
            }
            catch (Exception ex)
            {
                LogOpr.Error(ex.ToString());
            }
            return result;
        }

        /// <summary>
        /// 判断数据库中的某个字段的值是否存在
        /// </summary>
        /// <param name="strDbCode"></param>
        /// <param name="strField"></param>
        /// <param name="strFieldValue"></param>
        /// <returns>true:存在 false:不存在</returns>
        public DataTable IsOnlyOne(string strDbCode, string strField, string strFieldValue)
        {
            DataTable result = null; ;
            try
            {
                string strSql = "select sys_fld_sysid from " + strDbCode + "_METADATA where " + strField + "='" + strFieldValue.Trim() + "'";
                DataTable dt = Context.ExecuteSql(strSql);
                if (dt != null && dt.Rows.Count > 0)
                {
                    result = dt;
                }
            }
            catch (Exception ex)
            {
                LogOpr.Error(ex.ToString());
            }
            return result;
        }

        /// <summary>
        /// 获得论文提交数据库列表---LZG添加
        /// </summary>
        /// <param name="Flag"></param>
        /// <returns></returns>
        public IList<SYS_CMS_OPTION> GetSubmitDBList(int Flag)
        {
            IList<SYS_CMS_OPTION> result = null;
            try
            {
                //论文提交(flag=2)、在线提交(flag=1)
                ExpressionCombine<SYS_CMS_OPTION> exp = new ExpressionCombine<SYS_CMS_OPTION>();

                //if (SessionHelper.IsUserInfoExsit())
                //{
                //    ExpressionCombine<SYS_CMS_DATABASE> subExp2 = new ExpressionCombine<SYS_CMS_DATABASE>();
                //    IList<int> userDBInfo = SessionHelper.GetUserDBRight();
                //    if (userDBInfo != null && userDBInfo.Count > 0)
                //    {
                //        foreach (int item in userDBInfo)
                //        {
                //            subExp2.Or("SysID", OperatorType.Equal, item);
                //        }
                //        exp.And(subExp2);
                //    }
                //}
                exp.And("FLAG", OperatorType.Equal, Flag);
                result = Context.Get<SYS_CMS_OPTION>(exp.Compile());
            }
            catch (Exception ex)
            {
                LogOpr.Error(ex.ToString());
            }
            return result;
        }

        /// <summary>
        /// 返回DataTable类型信息---LZG添加
        /// </summary>
        /// <param name="strSql"></param>
        /// <returns></returns>
        public DataTable GetDataTableBySql(string strSql, int pageIndex, int pageSize, out int count, IList<SYS_CMS_DATABASE> selectDbList = null)
        {
            string connectStr = null;
            IList<SYS_CMS_DATABASE>  dblist = selectDbList.Where(c => c.SearchType != (int)SearchType.TPI).ToList();
            if (dblist != null && dblist.Count > 0)
            {
                connectStr = string.Format("serverIp={0};port={1};username={2};password={3}", dblist[0].VIP, dblist[0].VPort, dblist[0].VUserName, dblist[0].VPassWord);
            }
            return Context.ExecuteSql(strSql, pageIndex, pageSize, out count, connectStr: connectStr);
        }

        /// <summary>
        /// 返回DataTable类型信息---LZG添加
        /// </summary>
        /// <param name="strSql"></param>
        /// <returns></returns>
        public DataTable GetDataTableBySql(string strSql)
        {
            return Context.ExecuteSql(strSql);
        }

        /// <summary>
        /// 获得汉字拼音配置信息---LZG添加
        /// </summary>
        /// <param name="dbcode"></param>
        /// <returns></returns>
        public IList<SYS_CMS_HZTOPY> GetPYHZList(string dbcode)
        {
            IList<SYS_CMS_HZTOPY> result = null;
            try
            {
                string sql = @"select * from SYS_CMS_HZTOPY where  dbcode='{0}'";
                IList<SYS_CMS_HZTOPY> itemList = Context.ExecuteSql<SYS_CMS_HZTOPY>(string.Format(sql, dbcode));
                if (itemList != null && itemList.Count > 0)
                {
                    result = itemList;
                }
            }
            catch (Exception ex)
            {
                LogOpr.Error(ex.ToString());
            }
            return result;
        }

        /// <summary>
        /// 获得汉字拼音配置信息---LZG添加
        /// </summary>
        /// <param name="dbcode"></param>
        /// <returns></returns>
        public int GetFileCount(string dbcode, string fileName, int sysid = -1)
        {
            int result = 0;
            try
            {
                string sql = "";
                DataTable dt = null;
                if (-1 == sysid)
                {
                    sql = @"select count(*) from {0}_METADATA_FILE where FILENAME ='{1}'";
                    dt = Context.ExecuteSql(string.Format(sql, dbcode, fileName));
                }
                else
                {
                    sql = @"select count(*) from {0}_METADATA_FILE where FILENAME ='{1}' and (RECORDID=* not RECORDID = {2})";
                    dt = Context.ExecuteSql(string.Format(sql, dbcode, fileName, sysid));
                }

                if (dt != null && dt.Rows.Count > 0)
                {
                    result = int.Parse(dt.Rows[0][0].ToString());
                }
            }
            catch (Exception ex)
            {
                LogOpr.Error(ex.ToString());
            }
            return result;
        }

        /// <summary>
        /// 获得汉字拼音配置信息---LZG添加
        /// </summary>
        /// <param name="dbcode"></param>
        /// <returns></returns>
        public int UpdateUploadFileDate(string dbcode, string fileName)
        {
            int result = 0;
            try
            {
                string sql = @"update {0}_METADATA_FILE set  UPLOADTIME='" + DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss") + "' where FILENAME ='{1}'";
                result = Context.ExecuteSqlNonQuery(string.Format(sql, dbcode, fileName));
            }
            catch (Exception ex)
            {
                LogOpr.Error(ex.ToString());
            }
            return result;
        }

        /// <summary>
        /// 获得汉字拼音配置信息---LZG添加
        /// </summary>
        /// <param name="dbcode"></param>
        /// <returns></returns>
        public int UpdateUploadFileDOISortNo(string dbcode, int fileID, string doi, string sortNo)
        {
            int result = 0;
            try
            {
                string sql = @"update {0}_METADATA_FILE set DOI='{1}', SORTNUMBER='{2}' where sysid = {3}";
                result = Context.ExecuteSqlNonQuery(string.Format(sql, dbcode, doi, sortNo, fileID));
            }
            catch (Exception ex)
            {
                LogOpr.Error(ex.ToString());
            }
            return result;
        }

        /// <summary>
        /// 获得汉字拼音配置信息---LZG添加
        /// </summary>
        /// <param name="dbcode"></param>
        /// <returns></returns>
        public int UpdateFileInfo(string dbcode, string fileName, int id)
        {
            int result = 0;
            try
            {
                string sql = @"update {0}_METADATA set SYS_FLD_DIGITFILENAME='{1}' where sys_fld_sysid = {2}";
                result = Context.ExecuteSqlNonQuery(string.Format(sql, dbcode, fileName, id));
            }
            catch (Exception ex)
            {
                LogOpr.Error(ex.ToString());
            }
            return result;
        }

        /// <summary>
        /// 获得汉字拼音配置信息---LZG添加
        /// </summary>
        /// <param name="dbcode"></param>
        /// <returns></returns>
        public bool DeleteFileInfo(string dbcode, string fileName, int id)
        {
            bool result = false;
            try
            {
                string strSql = "delete from {0}_METADATA_FILE where FILENAME='{1}' and RECORDID = {2}";
                Context.ExecuteSqlNonQuery(string.Format(strSql, dbcode, fileName, id));
                result = true;
            }
            catch (Exception ex)
            {
                LogOpr.Error(ex.ToString());
            }
            return result;
        }

        /// <summary>
        /// 获得汉字拼音配置信息---LZG添加
        /// </summary>
        /// <param name="dbcode"></param>
        /// <returns></returns>
        public int InsertUploadFile(string dbcode, METADATA_FILE content)
        {
            int result = 0;
            try
            {
                string sql = @"insert into {0}_METADATA_FILE (RECORDID,RESOURCETYPE,FORMAT,CONTENTTYPE,UPLOADTIME,FILENAME,FILESIZE,MD5CODE,READONLINE,CONTENTFLAG) values ('{1}','{2}','{3}','{4}','{5}','{6}','{7}','{8}','{9}','{10}')";
                result = Context.ExecuteSqlNonQuery(string.Format(sql, dbcode, content.RECORDID, content.RESOURCETYPE, content.FORMAT, content.CONTENTTYPE, content.UPLOADTIME, content.FILENAME, content.FILESIZE, content.MD5CODE, content.READONLINE, content.CONTENTFLAG));
            }
            catch (Exception ex)
            {
                LogOpr.Error(ex.ToString());
            }
            return result;
        }

        /// <summary>
        /// 根据SQL语句执行相应操作
        /// </summary>
        /// <param name="strSql">SQL语句</param>
        /// <param name="CheckSMDBFlag">是否验证小语种数据库，true：验证 false：不验证</param>
        /// <returns>受影响行数</returns>
        public int ExecSql(string strSql, bool isUnicode)
        {

            int nRows = 0;
            try
            {
                if (isUnicode)
                {
                    strSql = "unicode:" + strSql;
                }
                nRows = Context.ExecuteSqlNonQuery(strSql);
            }
            catch (Exception ex)
            {
                LogOpr.Error(ex.ToString());
            }

            return nRows;
        }

        public IList<SYS_CMS_MEMBER_UNIT> GetMember_Unit()
        {
            return Context.GetAll<SYS_CMS_MEMBER_UNIT>();
        }

        public int UpdateMetaFileLink(string dbcode, int oldRecID, int newRecID)
        {
            string sql = "update {0}_METADATA_FILE set RECORDID = {1} where RECORDID = {2}";
            return Context.ExecuteSqlNonQuery(string.Format(sql, dbcode, newRecID, oldRecID));
        }

        public DataTable GetMetaInfo(string dbcode, int sysid)
        {
            string sql = "select SYS_FLD_RECORDADDDATE, SYS_FLD_DIGITFILENAME from {0}_METADATA where sys_fld_sysid = {1}";
            return Context.ExecuteSql(string.Format(sql, dbcode, sysid));
        }

        public int UpdateMetaInfo(string dbcode, int sysid, string addDate, string digitFileName)
        {
            string sql = "update {0}_METADATA set SYS_FLD_RECORDADDDATE='{1}', SYS_FLD_DIGITFILENAME='{2}' where sys_fld_sysid = {3}";
            return Context.ExecuteSqlNonQuery(string.Format(sql, dbcode, addDate, digitFileName, sysid));
        }

        public bool SaveFile(string srcFile, string targetFile)
        {
            return Context.SaveFile(srcFile, targetFile);
        }

        public bool DeleteFile(string filePath)
        {
            return Context.DeleteFile(filePath);
        }

        public IList<SYS_CMS_DATABASE_RELATION> GetSimilarList(string dbCode)
        {
            IList<SYS_CMS_DATABASE_RELATION> result = null;
            try
            {
                string sql = @"select SYSID,DBCODE,DBFIELD,RELATIONDBCODE,RELATIONDBFIELD,STATUS,SORTNO,TITLE
                                from SYS_CMS_DATABASE_RELATION
                                WHERE DBCODE='{0}' and STATUS = 1";
                result = Context.ExecuteSql<SYS_CMS_DATABASE_RELATION>(string.Format(sql, dbCode));
            }
            catch (Exception ex)
            {
                LogOpr.Error(ex.ToString());
            }
            return result;
        }
    }
}
